package com.hao.main;

import java.util.ArrayList;
import java.util.HashMap;

import GiaoHangVietNam.RawInfor.ClientControlMessage;
import GiaoHangVietNam.google.direction.GMapV2Direction;
import GiaoHangVietNam.google.direction.GetDirectionsAsyncTask;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.view.LayoutInflater;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;

public class GoogleMapActivity extends FragmentActivity implements
		OnClickListener, OnMarkerClickListener {

	GoogleMap googleMap;
	FooterButton backMapBtn, diretionBtn, detailBtn; 
	// địa chỉ khách hàng
	LatLng customerLocation = new LatLng(21.017054, 105.784185);
	String phoneNumber,customerName,companyName, listGoodsName;
	Boolean isSending;

	// Giao diện phần tương tác với marker
	LinearLayout clickedMarkerDetailLnl, fullLayoutClickedMarkerLnl;
	TextView shopNameTv, nameCustomerTv, listGoodsOfCustomerTv,
			statusInvoiceTv;
	Button callCustommerBtn;

	private Polyline newPolyline;
	// marker hiển thị người nhận;
	Marker markerCustomer;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.google_map_v2);
		// Getting reference to SupportMapFragment of the activity_main
		SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager()
				.findFragmentById(R.id.map);
		// Getting Map for the SupportMapFragment
		googleMap = fm.getMap();

		// Enable/Disable MyLocation Button in the Map
		googleMap.setMyLocationEnabled(true);
		// Enable/Disable Zoom Control
		googleMap.getUiSettings().setZoomControlsEnabled(false);
		googleMap.setOnMarkerClickListener(this);
		backMapBtn = (FooterButton) findViewById(R.id.footer_back_btn);
		backMapBtn.setText(getResources().getString(R.string.footer_back_btn));
		backMapBtn.setOnClickListener(this);
		diretionBtn = (FooterButton) findViewById(R.id.footer_diretions_google_btn);
		diretionBtn.setText(getResources().getString(
				R.string.footer_direction_btn));
		diretionBtn.setOnClickListener(this);
		detailBtn = (FooterButton) findViewById(R.id.footer_detail_from_map_btn);
		detailBtn.setText(getResources().getString(R.string.footer_detail_btn));
		detailBtn.setOnClickListener(this);
		
		// Lấy về các controls phần tương tác với marker
		getControlsClickedMarker();
		
		/** Lấy về các tham số, tên, số điện thoại, list hàng, nên truyền đối tượng sang */
		 getPara();
		 // Lấy về vị trí hiện tại và di chuyển camera về trung tâm;
		 getGPSByTracker();
		 findDirections(ClientControlMessage.CurrentGeo.latitude,ClientControlMessage.CurrentGeo.longitude,
		 customerLocation.latitude, customerLocation.longitude,
		 GMapV2Direction.MODE_DRIVING);
	}

	// Lấy về các controls phần tương tác với marker
	public void getControlsClickedMarker() {
		clickedMarkerDetailLnl = (LinearLayout)findViewById(R.id.clicked_marker_detail_lnl);
		fullLayoutClickedMarkerLnl = (LinearLayout)findViewById(R.id.full_layout_clicked_marker_lnl);
		fullLayoutClickedMarkerLnl.setOnClickListener(this);
		shopNameTv = (TextView)findViewById(R.id.name_shop_clicked_marker_tv);
		nameCustomerTv = (TextView)findViewById(R.id.name_customer_clicked_marker_tv);
		listGoodsOfCustomerTv = (TextView)findViewById(R.id.list_good_of_customer_click_marker_tv);
		statusInvoiceTv = (TextView)findViewById(R.id.status_invoice_clicked_marker_tv);
		callCustommerBtn = (Button)findViewById(R.id.call_customer__clicked_marker_btn);
		callCustommerBtn.setOnClickListener(this);
		
	}

	private void getPara() {
		// lấy intent gọi Activity này
		Intent callerIntent = getIntent();
		// có intent rồi thì lấy Bundle dựa vào MyPackage
		double lat = callerIntent.getDoubleExtra("Lat", 0);
		double lng = callerIntent.getDoubleExtra("Lng", 0);
		customerLocation = new LatLng(lat, lng);
		phoneNumber = callerIntent.getStringExtra("Number");
		customerName = callerIntent.getStringExtra("CustomerName");
		companyName = callerIntent.getStringExtra("CompanyName");
		isSending = callerIntent.getBooleanExtra("IsSending", true);
		listGoodsName = callerIntent.getStringExtra("ListGoodsName");
	}

	// Lấy về vị trí hiện tại
	private void getGPSByTracker() {   
		 
		/** Lấy về trung tâm bản đồ */
		googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
				customerLocation, 13));
		// địa chỉ customer lấy từ server
		
		// create marker
		View marker = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.custom_marker_layout, null);
		TextView nameRes = (TextView) marker.findViewById(R.id.info_restaurant_marker);
		// set tên người nhận vào marker, tăng tính trực quan
		nameRes.setText(customerName);
		 
		markerCustomer = googleMap.addMarker(new MarkerOptions()
		.position(customerLocation).
		icon(BitmapDescriptorFactory.fromBitmap(createDrawableFromView(this, marker))));
	}

	/** A class to parse the Google Places in JSON format */

	// lay ve thong tin duong di
	public void findDirections(double fromPositionDoubleLat,
			double fromPositionDoubleLong, double toPositionDoubleLat,
			double toPositionDoubleLong, String mode) {
		HashMap<String, String> map = new HashMap<String, String>();
		map.put(GetDirectionsAsyncTask.USER_CURRENT_LAT,
				String.valueOf(fromPositionDoubleLat));
		map.put(GetDirectionsAsyncTask.USER_CURRENT_LONG,
				String.valueOf(fromPositionDoubleLong));
		map.put(GetDirectionsAsyncTask.DESTINATION_LAT,
				String.valueOf(toPositionDoubleLat));
		map.put(GetDirectionsAsyncTask.DESTINATION_LONG,
				String.valueOf(toPositionDoubleLong));
		map.put(GetDirectionsAsyncTask.DIRECTIONS_MODE, mode);

		GetDirectionsAsyncTask asyncTask = new GetDirectionsAsyncTask(
				GoogleMapActivity.this);
		asyncTask.execute(map);
	}

	/** Ve duong di */
	public void handleGetDirectionsResult(ArrayList<LatLng> directionPoints) {
		PolylineOptions rectLine = new PolylineOptions().width(5).color(
				Color.RED);

		for (int i = 0; i < directionPoints.size(); i++) {
			rectLine.add(directionPoints.get(i));
		}
		if (newPolyline != null) {
			newPolyline.remove();
		}
		newPolyline = googleMap.addPolyline(rectLine);
		for (LatLng a : directionPoints) {
			Log.e("CAC DIEM RE", a.latitude + a.longitude + "");
		}
	}

	// add marker

	public MarkerOptions getMarker(LatLng point, int drawableId) {
		return new MarkerOptions().position(point).icon(
				BitmapDescriptorFactory.fromResource(drawableId));
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.footer_back_btn:
			finish();
			diretionBtn.setFooterFocus(false);
			detailBtn.setFooterFocus(false);
			break;
		case R.id.footer_diretions_google_btn:
			googleMap.clear();
			getGPSByTracker();
			findDirections(ClientControlMessage.CurrentGeo.latitude, ClientControlMessage.CurrentGeo.longitude,
					customerLocation.latitude, customerLocation.longitude,
					GMapV2Direction.MODE_DRIVING);
			diretionBtn.setFooterFocus(true);
			detailBtn.setFooterFocus(false);
			break;
		case R.id.footer_detail_from_map_btn:
		
			Toast.makeText(getApplicationContext(), "Lịch sử các đơn hàng !",
					Toast.LENGTH_SHORT).show();
			diretionBtn.setFooterFocus(false);
			detailBtn.setFooterFocus(true);
			break;
		case R.id.full_layout_clicked_marker_lnl:
			clickedMarkerDetailLnl.setVisibility(View.GONE);
			break;
		case R.id.call_customer__clicked_marker_btn:
			// Gọi tới người nhận
			callReceiver();
			break;
		default:
			break;
		}
	}
	public void callReceiver() {
		// Số điện thoại lấy từ DetailInvoiceActivity
		
		String uri = "tel:" + phoneNumber + "".trim();
		Intent intent = new Intent(Intent.ACTION_CALL);
		intent.setData(Uri.parse(uri));
		this.startActivity(intent);
	}

	@Override
	public boolean onMarkerClick(Marker arg0) {
		// TODO Auto-generated method stub
		if(arg0.equals(markerCustomer)) {
			
			// đang set dữ liệu giả cho phần tương tác với marker nếu click vào marker
			// dữ liệu được lấy từ getPara(); lấy các thuộc tính của đối tượng
			shopNameTv.setText(companyName);
			nameCustomerTv.setText(customerName);
			listGoodsOfCustomerTv.setText(listGoodsName);
			if(isSending==true)
				statusInvoiceTv.setText("Yêu cầu giao");
			else
				statusInvoiceTv.setText("Yêu cầu nhận");
			
			clickedMarkerDetailLnl.setVisibility(View.VISIBLE);
		}
		return false;
	}

	public static Bitmap createDrawableFromView(Context context, View view) {
		DisplayMetrics displayMetrics = new DisplayMetrics();
		((GoogleMapActivity) context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
		view.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		view.measure(displayMetrics.widthPixels, displayMetrics.heightPixels);
		view.layout(0, 0, displayMetrics.widthPixels, displayMetrics.heightPixels);
		view.buildDrawingCache();
		Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
 
		Canvas canvas = new Canvas(bitmap);
		view.draw(canvas);
 
		return bitmap;
	}
}
